package org.funtester.performance.books.chapter04.section3;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class RandomTool {

    /**
     * 获取随机字符串,包含大小写字母和数字,长度为 length
     * @param length 字符串长度
     * @return
     */
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; ++i) {
            int number = ThreadLocalRandom.current().nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 从列表中随机获取一个元素
     * @param list 元素集合
     * @return
     * @param <T>
     */
    public static <T> T getRandomElement(List<T> list) {
        int randomIndex = ThreadLocalRandom.current().nextInt(list.size());// 获取随机索引
        return list.get(randomIndex);// 获取随机元素
    }

}
